import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Table, Tag, Popconfirm } from 'antd';
import { Icon } from '@iconify/react';
import type { ColumnsType } from 'antd/es/table';
import { PageHeader } from '@/components';
import * as menuApi from './api';
import type { Menu, FormMode } from '@/types';
import type { MenuType } from './type';
import { useAuthStore } from '@/stores/useAuthStore';
import { useScrollHeight, useDictionary, useMessage } from '@/hooks';
import MenuFormModal from './modules/MenuFormModal';

const MenuManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [menus, setMenus] = useState<Menu[]>([]);
  const [formVisible, setFormVisible] = useState(false);
  const [formMode, setFormMode] = useState<FormMode>('create');
  const [currentMenu, setCurrentMenu] = useState<Menu | undefined>();

  const { hasPermission } = useAuthStore();
  const hasCreatePermission = hasPermission('menu:create');
  const hasEditPermission = hasPermission('menu:update');
  const hasDeletePermission = hasPermission('menu:delete');
  
  // 计算表格滚动高度
  const scrollY = useScrollHeight(280);
  
  // 加载菜单类型字典
  const { getLabel: getMenuTypeLabel } = useDictionary({ code: 'menu_type' });
  
  // 使用 message API
  const message = useMessage();

  // 获取菜单列表
  const fetchMenus = async () => {
    setLoading(true);
    try {
      const response = await menuApi.getMenuTree();
      if (response.data.success) {
        setMenus(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch menus:', error);
      message.error('获取菜单列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMenus();
  }, []);

  // 新增
  const handleCreate = (parentId?: string) => {
    setFormMode('create');
    setCurrentMenu(parentId ? { parentId } as Menu : undefined);
    setFormVisible(true);
  };

  // 编辑
  const handleEdit = (record: Menu) => {
    setFormMode('edit');
    setCurrentMenu(record);
    setFormVisible(true);
  };

  // 删除
  const handleDelete = async (id: string) => {
    try {
      await menuApi.deleteMenu(id);
      message.success('删除成功');
      fetchMenus();
    } catch (error) {
      console.error('Failed to delete menu:', error);
      message.error('删除失败');
    }
  };

  // 表单提交
  const handleFormSubmit = async (values: any) => {
    try {
      const data = {
        ...values,
        parentId: values.parentId || null,
      };

      if (formMode === 'create') {
        await menuApi.createMenu(data);
        message.success('创建成功');
      } else {
        await menuApi.updateMenu({ ...data, id: currentMenu!.id });
        message.success('更新成功');
      }
      setFormVisible(false);
      fetchMenus();
    } catch (error) {
      console.error('Failed to save menu:', error);
      message.error(formMode === 'create' ? '创建失败' : '更新失败');
    }
  };


  // 表格列配置
  const columns: ColumnsType<Menu> = [
    {
      title: '菜单名称',
      dataIndex: 'title',
      key: 'title',
      width: 220,
      render: (text: string, record) => (
        <Space>
          {record.icon ? (
            <Icon icon={record.icon} style={{ fontSize: '18px', color: '#1890ff' }} />
          ) : (
            <span style={{ display: 'inline-block', width: '18px' }} />
          )}
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '英文名称',
      dataIndex: 'english',
      key: 'english',
      width: 180,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: MenuType) => {
        const typeMap: Record<MenuType, { color: string }> = {
          directory: { color: 'blue' },
          menu: { color: 'green' },
          button: { color: 'orange' },
        };
        const config = typeMap[type];
        return <Tag color={config.color}>{getMenuTypeLabel(type)}</Tag>;
      },
    },
    {
      title: '路由路径',
      dataIndex: 'path',
      key: 'path',
      width: 200,
    },
    {
      title: '权限标识',
      dataIndex: 'permission',
      key: 'permission',
      width: 150,
      render: (text: string) => text && (
        <code style={{ 
          padding: '2px 6px', 
          background: 'rgba(0,0,0,0.06)', 
          borderRadius: '4px',
          fontSize: '12px'
        }}>
          {text}
        </code>
      ),
    },
    {
      title: '排序',
      dataIndex: 'orderNum',
      key: 'orderNum',
      width: 80,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: boolean) => (
        <Tag color={status ? 'success' : 'default'}>
          {status ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 240,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          {hasCreatePermission && record.type !== 'button' && (
            <Button
              type="link"
              size="small"
              icon={<Icon icon="solar:add-circle-linear" />}
              onClick={() => handleCreate(record.id)}
            >
              新增
            </Button>
          )}
          {hasEditPermission && (
            <Button
              type="link"
              size="small"
              icon={<Icon icon="solar:pen-linear" />}
              onClick={() => handleEdit(record)}
            >
              编辑
            </Button>
          )}
          {hasDeletePermission && (
            <Popconfirm
              title="确定要删除这个菜单吗？"
              description="删除后子菜单也会被删除"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                size="small"
                danger
                icon={<Icon icon="solar:trash-bin-minimalistic-linear" />}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];
  
  return (
    <div>
      <PageHeader
        title="菜单管理"
        extra={
          hasCreatePermission && (
            <Button
              type="primary"
              icon={<Icon icon="solar:add-circle-linear" />}
              onClick={() => handleCreate()}
            >
              新增菜单
            </Button>
          )
        }
      />
      <Card>
        <Table
          columns={columns}
          dataSource={menus}
          loading={loading}
          rowKey="id"
          pagination={false}
          scroll={{ y: scrollY, x: 'max-content' }}
          expandable={{
            defaultExpandAllRows: true,
          }}
        />
      </Card>

      {/* 菜单表单 */}
      <MenuFormModal
        visible={formVisible}
        mode={formMode}
        menus={menus}
        initialValues={currentMenu}
        onSubmit={handleFormSubmit}
        onCancel={() => setFormVisible(false)}
      />
    </div>
  );
};

export default MenuManagement;

